import { Text, View, StyleSheet, Button, Pressable, TextInput } from 'react-native';
import React, { useState, useRef, useEffect } from 'react';

interface IStepperProps {
  isInput: boolean;
  number: number;
  onGetNum: (values: number) => void;
}

const Stepper: React.FC<IStepperProps> = ({ isInput, number, onGetNum }) => {
  let [num, setNum] = useState<number>(number);

  //当开启输入时校验方法
  const inputVerify = (text: string | undefined) => {
    let nText = Number(text);
    if (Number.isInteger(nText) && nText > 0) {
      setNum(nText);
    } else {
      setNum(1);
    }
  };

  const numberClick = (type: string, val?: string | undefined) => {
    switch (type) {
      case 'add':
        setNum(num + 1);
        break;
      case 'remove':
        setNum(num - 1);
        break;
    }
  };

  useEffect(() => {
    onGetNum(num);
  }, [num]);

  return (
    <View style={styles.flexView}>
      <View style={[styles.removeBtn, styles.comBtn]}>
        <Pressable
          onPress={() => {
            numberClick('remove');
          }}
          disabled={num == 1}
        >
          <Text style={styles.comText}>－</Text>
        </Pressable>
      </View>
      <View style={[styles.comBtn, styles.numView]}>
        {isInput ? (
          // 这里放置你的输入组件，比如 TextInput
          <TextInput
            style={styles.inputNum}
            placeholder=""
            keyboardType="number-pad"
            selectTextOnFocus
            onChangeText={(text) => {
              inputVerify(text);
            }}
            value={String(num)}
          />
        ) : (
          <Text style={styles.comText}>{num}</Text>
        )}
      </View>
      <View style={[styles.addBtn, styles.comBtn]}>
        <Pressable
          onPress={() => {
            numberClick('add');
          }}
        >
          <Text style={styles.comText}>＋</Text>
        </Pressable>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  flexView: {
    flexDirection: 'row',
    width: 100,
    marginLeft: 10,
    marginRight: 10,
  },
  comBtn: {
    width: 32,
    height: 32,
    backgroundColor: '#f2f3f5',
    borderRadius: 3,
    justifyContent: 'center',
  },
  comText: {
    textAlign: 'center',
    fontSize: 18,
    fontWeight: 'bold',
  },
  removeBtn: {},
  addBtn: {},

  numView: {
    width: 36,
    fontSize: 16,
    marginLeft: 3,
    marginRight: 3,
    borderRadius: 0,
  },
  inputNum: {
    width: 24,
    padding: 0,
    marginLeft: 6,
    marginRight: 6,
    textAlign: 'center',
  },
});

export default Stepper;
